package JZOffer;

/**
 * @author Lw中
 * @date 2021/8/11 22:58
 */
public class Jz22 {

    // Jz22.链表中倒数第K个节点
     public class ListNode {
         int val;
         ListNode next;
         ListNode(int x) { val = x; }
     }

    public ListNode getKthFromEnd(ListNode head, int k) {
        // 双指针的做法
        ListNode former = head, letter = head;
        // 让former走k个节点
        for (int i = 0; i < k; i++) {
            former = former.next;
        }
        // 然后让f、l同时走n-k个节点
        while (former != null) {
            former = former.next;
            letter = letter.next;
        }
        return letter;
    }

}
